const mongoose = require('mongoose')
const uuidv4 = require('uuid/v4')
const Menu = require('../Models/Menu')
const { getParam, getIP, isNoToken, isInArray } = require('../lib/utils')

mongoose.Promise = global.Promise
var promise = mongoose.connect('mongodb://127.0.0.1:27017/BMS', {
  useMongoClient: true
  /* other options */
})
var db = mongoose.connection

// console.log(Promise)
// const findAsync = Promise.promisify(Menu.find)

// 默认菜单只设两个层级

// get all menu list
const getMenu = (req, res) => {
  if (isNoToken(req, res)) return
  const resultList = ['_id', 'pid', 'icon', 'label', 'uri', 'order', 'isShow', 'isDevShow']
  Menu.find({}, resultList, function (err, data) {
    if (err) {
      return res.json({code: -1, message: `something wrong, error: ${err.message}`})
    }
    res.json({code: 0, message: 'success', data: data})
  })
}

// update by id
const updateMenuById = (req, res) => {
  if (isNoToken(req, res)) return

  const { id } = getParam(req, ['id'])
  if (!id) {
    return res.json({code: -1, message: 'error!, no id passed!'})
  }

  // get the list of parameters, translate them to a object, and filter empty value 
  const list = ['pid', 'icon', 'label', 'uri', 'isShow', 'isDevShow', 'description', 'order']
  const result = getParam(req, list)

  if (result.pid === id) {
    return res.json({code: -1, message: 'pid can not as same as the id'})
  }

  let obj = Object.assign(result, {updateIP: getIP(req)})
  obj = JSON.parse(JSON.stringify(obj))

  // start update values
  Menu.update({_id: id}, {'$set': obj}, function (err) {
    if (err) {
      return res.json({code: -1, message: `fail to update, error: ${err.message}`})
    }
    res.json({code: 0, message: 'success', data: obj})
  })
}

// find item by id
const findMenuById = (req, res) => {
  if (isNoToken(req, res)) return
  const { id } = getParam(req, ['id'])
  Menu.find({_id: id}, function (err, data) {
    if (err) {
      return res.json({code: -1, message: `fail to find menu, error: ${err.message}`})
    }
    if (data.length === 0) {
      return res.json({code: -1, message: 'menu is not exist, please check the \'id\' is correct'})
    }
    res.json({code: 0, message: 'success', data: data})
  })
}

// add new menu, save menu
const saveMenu = (req, res) => {
  if (isNoToken(req, res)) return
  const list = ['pid', 'label', 'icon', 'uri', 'isShow', 'isDevShow', 'description', 'order']
  const result = getParam(req, list)
  let obj = Object.assign(result, {createIP: getIP(req), _id: uuidv4()})
  obj = JSON.parse(JSON.stringify(obj)) // ready to save
  console.log(obj)

  // verify...
  // label can not be empty
  if (!obj.label || obj.label === '') {
    return res.json({code: -1, message: 'label is empty'})
  }

  const { pid, label } = obj
  Menu.find({label: label}, function (error, data) {
    if (error) return res.json({code: -1, message: 'fail to save menu, error info0: ' + error.message})
    // check label first
    if (isInArray(data, 'label', label)) {
      // if label value is exist, can not be saved
      return res.json({code: -1, message: 'fail to save menu, error info1: label must be unique'})
    }

    if (!pid) {
      // strat save data
      const menuInfo = new Menu(obj)
      menuInfo.save(e => {
        if (e) return res.json({code: -1, message: 'fail to save menu, error info3: ' + e.message})
        res.json({code: 0, message: 'success', data: obj})
      })
    } else {
      Menu.find({_id: pid}, function (err, dd) {
        if (err) return res.json({code: -1, message: 'fail to save menu, error info2: ' + err.message})
        // check the parent id is exist
        if (!isInArray(dd, '_id', pid)) {
          return res.json({code: -1, message: 'fail to save menu, error info: the parent id is not exist'})
        }

        // if other check...
        // strat save data
        const menuInfo = new Menu(obj)
        menuInfo.save(e => {
          if (e) return res.json({code: -1, message: 'fail to save menu, error info3: ' + e.message})
          res.json({code: 0, message: 'success', data: obj})
        })
      })
    }
  })
}

// remove by id, require an array of ids
const removeMenuById = (req, res) => {
  if (isNoToken(req, res)) return

  const { ids } = getParam(req, ['ids'])
  if (!ids || ids.length === 0) {
    return res.json({code: -1, message: 'error!, no id passed!'})
  }

  Menu.remove({_id: {$in: ids}}, function (err, data) {
    if (err) return res.json({code: -1, message: 'fail to remove, error info: ' + err.message})
    if (!data) return res.json({code: -1, message: 'fail to remove, item does not exist.'})
    res.json({code: 0, message: 'success'})
  })
}

module.exports = {
  getMenu,
  updateMenuById,
  findMenuById,
  saveMenu,
  removeMenuById
}
